from datetime import datetime, timedelta


def get_result(analyze_df, continue_days=(2, 8), recently_days=365, increased_ratio=0.2) -> (dict, dict):
    """从2个维度，统计历史的涨跌:
        1. 连续n天上涨/下跌之后，n+1天下跌/上涨的次数；
        2. 放量上涨/下跌之后，第二天继续上涨/下跌的次数；
    """
    statistics = {str(i): {
        "decline_total_count": 0,  # 连续n天下跌的总次数
        "decline_rise_count": 0,  # 连续n天下跌后第三天上涨的次数
        "rise_total_count": 0,  # 连续n天上涨的总次数
        "rise_decline_count": 0,  # 连续n天上涨后第三天下跌的次数
        "recently_decline_total_count": 0,  # 近期连续n天下跌的总次数
        "recently_decline_rise_count": 0,  # 近期连续n天下跌后第三天上涨的次数
        "recently_rise_total_count": 0,  # 近期连续n天上涨的总次数
        "recently_rise_decline_count": 0,  # 近期连续n天上涨后第三天下跌的次数
    } for i in range(continue_days[0], continue_days[1]+1)}

    increased_trading = {
        "decline_count": 0,         # 放量下跌的总次数
        "then_continue_decline_count": 0,      # 放量下跌后，第二天继续下跌的次数
        "raise_count": 0,           # 放量上涨的总次数
        "then_continue_raise_count": 0,    # 放量上涨后，第二天上涨的次数
    }

    total = len(analyze_df)
    recently_date = (datetime.now() - timedelta(recently_days)).strftime("%Y-%m-%d")
    for i in range(total):
        # 连续涨跌之后的数据统计
        for (day, item) in statistics.items():
            day = int(day)
            if i + day < total:
                # 重头开始统计
                if all(analyze_df.iloc[j]["涨跌额"] < 0 for j in range(i, i + day)):  # 连跌n天
                    item["decline_total_count"] += 1
                    if analyze_df.iloc[i + day]["涨跌额"] > 0:
                        item["decline_rise_count"] += 1
                if all(analyze_df.iloc[j]["涨跌额"] > 0 for j in range(i, i + day)):  # 连涨n天
                    item["rise_total_count"] += 1
                    if analyze_df.iloc[i + day]["涨跌额"] < 0:
                        item["rise_decline_count"] += 1

                # 统计最近n天的数据
                if analyze_df.iloc[i]["日期"] >= recently_date:
                    if all(analyze_df.iloc[j]["涨跌额"] < 0 for j in range(i, i + day)):  # 连跌n天
                        item["recently_decline_total_count"] += 1
                        if analyze_df.iloc[i + day]["涨跌额"] > 0:
                            item["recently_decline_rise_count"] += 1
                    if all(analyze_df.iloc[j]["涨跌额"] > 0 for j in range(i, i + day)):  # 连涨n天
                        item["recently_rise_total_count"] += 1
                        if analyze_df.iloc[i + day]["涨跌额"] < 0:
                            item["recently_rise_decline_count"] += 1
        # 放量之后的数据统计
        if i + 1 < total and analyze_df.iloc[i + 1]["成交额"] > analyze_df.iloc[i]["成交额"]:  # 放量
            r = round((analyze_df.iloc[i + 1]["成交额"] - analyze_df.iloc[i]["成交额"]) / analyze_df.iloc[i]["成交额"], 2)
            if r > increased_ratio:
                if analyze_df.iloc[i]["涨跌额"] < 0:  # 放量下跌
                    increased_trading["decline_count"] += 1
                    if analyze_df.iloc[i+1]["涨跌额"] < 0:  # 放量下跌，继续下跌
                        increased_trading["then_continue_decline_count"] += 1
                elif analyze_df.iloc[i]["涨跌额"] > 0:
                    increased_trading["raise_count"] += 1
                    if analyze_df.iloc[i+1]["涨跌额"] > 0:
                        increased_trading["then_continue_raise_count"] += 1

    return statistics, increased_trading


def get_trend_and_continue_days(analyze_df, max_day=8) -> (None | bool, float, int):
    """获取最近几天的上升或下降趋势，以及持续上升、下降了几天, 放量了多少"""
    continue_days = 0
    ratio = 0.0
    is_raise_trend = None  # 上涨或下跌的趋势
    for i in range(1, max_day+1):
        if i == 1:
            ratio = round((analyze_df.iloc[-1]["成交额"] - analyze_df.iloc[-2]["成交额"]) / analyze_df.iloc[-2]["成交额"],
                          2)
        if analyze_df.iloc[-i]["涨跌额"] < 0:
            if is_raise_trend is None or is_raise_trend is False:
                is_raise_trend = False
                continue_days = i
            else:
                break
        elif analyze_df.iloc[-i]["涨跌额"] > 0:
            if is_raise_trend is None or is_raise_trend:
                is_raise_trend = True
                continue_days = i
            else:
                break
    return is_raise_trend, ratio, continue_days
